<template>
  <div class='question-container'>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>试题录入</span>
      </div>
      <div>
        <el-form :model="subjectForm" :rules="rules" ref="subjectForm" label-width="120px" class="question-form">
        <!-- 学科 -->
        <el-form-item  label="学科:" prop="subjectID" >
          <el-select  v-model="subjectForm.subjectID" placeholder="请选择" @change="handelCatalog" >
              <el-option v-for="item in subjectList" :key="item.value" :label="item.label"  :value="item.value" ></el-option>
          </el-select>
        </el-form-item>
        <!-- 目录 -->
        <el-form-item label="目录:" prop="catalogID">
          <el-select v-model="subjectForm.catalogID" placeholder="请选择">
            <el-option v-for="item in catalogList" :key="item.id" :label="item.directoryName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 企业 -->
        <el-form-item label="企业:" prop="enterpriseID">
          <el-select v-model="subjectForm.enterpriseID" placeholder="请选择">
            <el-option v-for="item in companysList" :key="item.id" :label="item.company" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 城市 -->
        <!-- <el-form-item label="城市:" prop="province">  注意:要想使得省份和城市都要实现规则匹配--这里的校验规则就得是下一级的city(由于2者有联动,必须得先有province才能去继续选中city--所以,这里直接校验city即可!!!-->
        <el-form-item label="城市:" prop="city">
          <el-select style="width:198px" v-model="subjectForm.province" placeholder="请选择"  @change="handleProvince">
            <el-option v-for="item in citySelect.province" :key="item" :label="item" :value="item"></el-option>
          </el-select>

          <el-select style="width:198px;margin-left: 4px;" v-model="subjectForm.city" placeholder="请选择">
            <el-option v-for="item in citySelect.cityDate" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <!-- 方向 -->
        <el-form-item label="方向:" prop="direction">
          <el-select v-model="subjectForm.direction" placeholder="请选择">
            <el-option v-for="item in directionList" :key="item" :label="item" :value="item"></el-option>

          </el-select>
        </el-form-item>
        <!-- 题型 -->
        <el-form-item label="题型:" prop="questionType">
          <!-- @change="changeRadio({}) 执行此函数--使得切换回单选类型时,没有默认上次选中的选项!!! -->
          <el-radio-group v-model="subjectForm.questionType" @change="changeRadio({})">
           <el-radio v-for="item in questionTypeList" :key="item.value" :label="item.value+''" >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 难度 -->
        <el-form-item label="难度:" prop="difficulty">
          <el-radio-group v-model="subjectForm.difficulty">
           <el-radio v-for="item in difficulty" :key="item.value"  :label="item.value+''" >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 题干 -->
        <el-form-item label="题干:" prop="question">
           <quill-editor  v-model="subjectForm.question" :options="editorOptions"></quill-editor>
        </el-form-item>

        <!-- 选项 需要分情况和试题类型关联-->
        <!-- <el-form-item label="选项：" prop="options" v-if="subjectForm.questionType!=='3'">  我看项目需求上没有这项的校验---所以这里就不校验这项了-->
        <el-form-item label="选项：" v-if="subjectForm.questionType!=='3'">
          <!-- <div class="option_item" v-for="item in subjectForm.options" :key="item.code"> -->
          <div class="option_item" v-for="(item,index) in subjectForm.options" :key="item.code">
            <!-- <el-radio v-if="subjectForm.questionType==='1'"  v-model="item.isRight" style="margin-right:0" :label="true">{{item.code}}：</el-radio> -->

            <!-- 设置@change="changeRadio(item)事件函数--使得产生单选效果!! -->
            <el-radio v-if="subjectForm.questionType==='1'" @change="changeRadio(item)" v-model="item.isRight" style="margin-right:0" :label="true">{{item.code}}：</el-radio>
            <el-checkbox v-if="subjectForm.questionType==='2'" v-model="item.isRight" style="margin-right:0" :label="true">{{item.code}}：</el-checkbox>
            <el-input v-model="item.title" style="width:356px"></el-input>

            <!-- <ImageUpload  @changeImg="imgURL(index,$event)" :img=item.img ></ImageUpload> -->
            <ImageUpload  @changeImg="imgURL(index,$event)" :img=item.img v-if="$route.query.id"></ImageUpload>
            <ImageUpload  @changeImg="imgURL(index,$event)"  v-else></ImageUpload>
          </div>
          <!-- 添加按钮 -->
          <el-button type="danger" :disabled="subjectForm.questionType!=='2'" @click="addClick" size="small">+增加选项与答案</el-button>
        </el-form-item>

        <el-form-item label="解析视频:">
          <el-input v-model="subjectForm.videoURL"></el-input>
        </el-form-item>
        <!-- 答案解析 -->
        <el-form-item label="答案解析:" prop="answer">
          <quill-editor  v-model="subjectForm.answer" :options="editorOptions"></quill-editor>
        </el-form-item>
        <!-- 题目备注 -->
        <el-form-item label="题目备注:">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            v-model="subjectForm.remarks"
            style="width:400px; "
            >
          </el-input>
        </el-form-item>
        <el-form-item label="试题标签:">
          <el-select multiple v-model="subjectForm.tags" placeholder="请选择试题标签">
            <el-option v-for="item in tagList" :key="item.value"  :label="item.label" :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 确认提交/修改 -->
        <!--  ---注意判断:是 添加 还是 修改 : 可以通过是否能获取当前页面的路由 -->
        <el-form-item v-if="true">
         <el-button v-if="!$route.query.id" @click="submit()" type="primary">确认提交</el-button>
          <el-button v-else @click="alter()" type="success">确认修改</el-button>
        </el-form-item>
      </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
// 导入上传图片组件
import ImageUpload from '@/module-hmmm/components/ImageUpload'
// 导入富文本组件
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'

// 导入简单学科列表请求
import { simple } from '@/api/hmmm/subjects.js'
// 导入 方向 + 题型 + 难度
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
// 导入企业请求
import { list } from '@/api/hmmm/companys.js'
// 导入城市
import { provinces, citys } from '@/api/hmmm/citys.js'
// 导入目录请求并重命名
import { list as reqCataloglist } from '@/api/hmmm/directorys.js'
// 导入简单标签请求并重命名
import { simple as reqTagList } from '@/api/hmmm/tags.js'
// 导入题库的相关操作
import { add, update, detail } from '@/api/hmmm/questions.js'
export default {
  name: 'QuestionsNew',
  components: {
    ImageUpload,
    quillEditor
  },
  data () {
    return {
      editorOptions: {
        placeholder: '请输入内容....',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote'], // 引用，
            ['code-block', 'image', 'link']// 代码块 、上传图片、链接
          ],
          // 语法高亮
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      },
      subjectForm: {
        subjectID: null, // 学科名称id
        catalogID: null, // 目录id
        enterpriseID: null, // 企业id
        province: '', // 城
        city: '', // 地区
        direction: '', // 方向
        tags: '', // 标签
        questionType: '1', // 题型,我这里设置一个默认值
        difficulty: '1', // 难度,我这里设置一个默认值
        question: '', // 题干
        // title:收集input的输入内容  isRight:表示是否是正确答案----点击选中则isRight的值会变成true,表示是正确答案
        options: [
          { code: 'A', title: '', img: '', isRight: false },
          { code: 'B', title: '', img: '', isRight: false },
          { code: 'C', title: '', img: '', isRight: false },
          { code: 'D', title: '', img: '', isRight: false }
        ],
        answer: '', // 答案解析
        remarks: '', // 题目备注
        videoURL: '' // 解析视频
      },
      subjectList: [], // 学科列表
      directionList: direction, // 方向列表
      companysList: [], // 企业列表
      catalogList: [], // 目录列表
      tagList: [], // 标签列表
      questionTypeList: questionType, // 题型
      difficulty, // 难度
      citySelect: { // 城市
        province: [],
        cityDate: []
      },

      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        // tags: [
        //   { required: true, message: '请选择标签', trigger: 'change' }
        // ], 我看项目需求上没有这项的校验---所以这里就注释掉了
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'change' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'change' }
        ]

      }
    }
  },
  created () {
    this.getSubjectList()
    // this.getList(this.subjectID)
    this.getCompanysList()
    this.getCityData()

    if (this.$route.query.id) {
      this.getQuestion()
    }
  },

  methods: {
    // 获取学科列表
    async getSubjectList () {
      // const res = await simple()
      const { data } = await simple()
      // console.log(data, '11111')
      this.subjectList = data
    },
    // 获取目录列表
    async getList (id) {
      // 获取目录列表
      const { data: data1 } = await reqCataloglist({ subjectID: id })
      // console.log(data1, '22222')
      this.catalogList = data1.items
      // 获取标签列表
      const { data: data2 } = await reqTagList({ subjectID: id })
      // console.log(data2, '33333')
      this.tagList = data2
    },
    // 学科改变后
    handelCatalog (id) {
      // this.subjectForm.catalog = ''
      // console.log(id) 注意:这个id值就等于subjectID
      // console.log(id)
      this.getList(id)
    },
    // 获取企业列表
    async getCompanysList () {
      const { data } = await list()
      // console.log(data)
      this.companysList = data.items
    },
    // 获取所有省份
    getCityData () {
      this.citySelect.province = provinces()
    },
    // 获取省份所对应的市(事件对象e表示被点击的省份):
    handleProvince (e) {
      // console.log(e)
      // this.subjectForm.province = e  上面标签中已绑定了,所以这边就不用再重新赋值了
      this.citySelect.cityDate = citys(e)
    },
    // 获取图片地址
    imgURL (index, url) {
      // console.log(url)
      // console.log(index)
      this.subjectForm.options[index].img = url
    },

    // 添加选项
    addClick () {
      // String.fromCharCode(65)--是获取大写字母的方法,65为起始值,表示获取的是A. 之后的数值每+1,表示下一个大写的英文字母
      // console.log(String.fromCharCode(65))
      this.subjectForm.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.subjectForm.options.length),
        title: '',
        img: ''
      })
    },
    // 设置@change="changeRadio(item)事件函数--使得产生单选效果!!
    changeRadio (item) {
      // 1. 清除所有的选中
      this.subjectForm.options.forEach(item => {
        item.isRight = false
      })
      // 2. 自己选中
      item.isRight = true
    },

    // 获取题目信息
    async getQuestion () {
      const { data } = await detail({ id: this.$route.query.id })
      console.log(data)
      data.tags = data.tags.split(',')

      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })

      this.subjectForm = data
      // const { data: data1 } = await reqCataloglist({ subjectID: this.subjectForm.subjectID })
      // this.catalogList = data1.items
      // const { data: data2 } = await reqTagList({ subjectID: this.subjectForm.subjectID })
      // this.tagList = data2
      this.getList(this.subjectForm.subjectID)

      // 滚动顶部
      this.$nextTick(() => {
        window.scrollTo(0, 0)
      })
    },
    // 提交
    submit () {
      this.$refs.subjectForm.validate(async (flag) => {
        if (!flag) {
          this.$message.error('请完成填写')
        } else {
          const data = { ...this.subjectForm }
          // 注意:因为接口文档中,基础题库的添加,参数要求中,tags得是字符串类型--所以,这里使用了一个数组的join方法---将数组内所以元素按指令符号拼接成字符串!!!否则会报错
          data.tags = data.tags.join(',')
          // console.log(data)
          const res = await add(data)
          console.log(res)
          this.$message.success('添加成功')
          this.$router.push('/questions/list')
        }
      })
    },
    // 修改
    async alter () {
      this.$refs.subjectForm.validate(async (flag) => {
        if (flag) {
          const data = { ...this.subjectForm }
          data.tags = data.tags.join(',')
          // console.log(data)  data对象里有id值--所以下面的方法调用中,直接传递data对象即可!
          const res = await update(data)
          console.log(res)
          this.$message.success('修改成功')
          this.$router.push('/questions/list')
        }
      })
    }

  }

}
</script>

<style scoped lang='scss'>
.question-container{
padding:20px;
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 100%;
  }
  // .question-form{
  //   width:540px
  // }
 ::v-deep {
  .el-select {
    height: 36px;
    width:400px;

  }
  .el-textarea__inner{
    min-height: 100px;
  }
  // .el-input{
  //   width:356px;
  // }
  // .el-select-dropdown__empty{
  //   display: none;
  // }
  .option_item{
    padding-bottom: 20px;
  }
  .ql-editor{
    height: 200px;
}
}
}
  </style>
